package com.squirrel.michale;


import java.util.Arrays;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/3/23 7:17 AM
 * @company Michale Squirrel
 * @link
 * @description
 */
public class LeetCode0948 {

    public int bagOfTokensScore(int[] tokens, int power) {
        // token sort
        Arrays.sort(tokens);
        int result = 0;
        int points = 0;
        int left = 0;
        int right = tokens.length - 1;
        while (left <= right) {
            // 用能量换分数
            if (power >= tokens[left]) {
                power -= tokens[left];
                left++;
                points++;
                result = Math.max(result, points);
            } else if (points > 0) {
                // 用分数换能量
                power += tokens[right];
                right--;
                points--;
            }else {
                break;
            }
        }
        return result;

    }
}
